/*


 */

package jas.http.server;

import jas.http.logging.HttpLogger;
import jas.http.response.HttpResponseFactory;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 *
 */
public class HttpServer implements Runnable {
    
    private ServerSocket serverSocket;
    private int port;
    private HttpLogger logger;
    private ConnectionHandler connectionHandler;
    private volatile boolean stop = false;
    private volatile boolean isStopped = false;
    private HttpServerSocketFactory socketFactory = new HttpSeverSocketFactoryImpl();
    
    public void stop() {
        stop = true;
        try {
            if (serverSocket != null) {
                serverSocket.close();
            }
            while (!isStopped) {
                Thread.sleep(10);
            }
        } catch (InterruptedException ex) {
            Logger.getLogger(HttpServer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(HttpServer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public HttpServer(HttpServerFactory httpServerFactory) {
        logger = httpServerFactory.createLogger();
        port = httpServerFactory.getListenPort();
        connectionHandler = httpServerFactory.createConnectionHandler();
    }
    
    public HttpServer(int port, ConnectionHandler connectionHandler) {
        logger = new NullLogger();
        this.port = port;
        this.connectionHandler = connectionHandler;
    }
    
    public void run() {
        try {
            serverSocket = socketFactory.createSocket(port);
            port = serverSocket.getLocalPort();
            logger.log("Server listenening on port: "+ port);
            while (!stop) {
                try {
                    Socket clientSocket = serverSocket.accept();

                    connectionHandler.handleConnection(clientSocket);
                } catch (SocketException se) {
                } 
            }
            serverSocket.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        isStopped = true;
        connectionHandler.stop();
    }
    
    
    public static void main(String[] args) {
        HttpServer server = new HttpServer(new StdHttpServerFactory());
        server.run();
    }
}
